/*=============================================================================

  Library: CFS

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=============================================================================*/

#include "CFSPluginConstants.h"
#include "CFSPluginContext.h"
#include "CFSPluginContext_p.h"
#include "CFSPluginFramework.h"
#include "CFSPluginFrameworkLauncher.h"

#include "CFSLocationManager_p.h"
#include "CFSPluginFramework_p.h"
#include "CFSPluginFrameworkContext_p.h"
#include "CFSPluginFrameworkUtil_p.h"
#include "CFSPluginFrameworkDebugOptions_p.h"

#include "CFSBasicLocation_p.h"

#include <QtConcurrentRun>

//----------------------------------------------------------------------------
CFSPluginFrameworkPrivate::CFSPluginFrameworkPrivate(QWeakPointer<CFSPlugin> qq, CFSPluginFrameworkContext* fw)
  : CFSPluginPrivate(qq, fw, 0, CFSPluginConstants::SYSTEM_PLUGIN_LOCATION,
                     CFSPluginConstants::SYSTEM_PLUGIN_SYMBOLICNAME,
                     // TODO: read version from the manifest resource
                     CFSVersion(0, 9, 0)),
    shuttingDown(0)
{
  systemHeaders.insert(CFSPluginConstants::PLUGIN_SYMBOLICNAME, symbolicName);
  systemHeaders.insert(CFSPluginConstants::PLUGIN_NAME, location);
  systemHeaders.insert(CFSPluginConstants::PLUGIN_VERSION, version.toString());
}

//----------------------------------------------------------------------------
void CFSPluginFrameworkPrivate::init()
{
  this->state = CFSPlugin::STARTING;
  this->fwCtx->init();
}

//----------------------------------------------------------------------------
void CFSPluginFrameworkPrivate::initSystemPlugin()
{
  this->pluginContext.reset(new CFSPluginContext(this));
}

//----------------------------------------------------------------------------
void CFSPluginFrameworkPrivate::activate(CFSPluginContext* context)
{
  CFSProperties locationProperties;
  CFSBasicLocation* location = CFSLocationManager::getUserLocation();
  if (location != NULL)
  {
    locationProperties["type"] =  CFSPluginFrameworkLauncher::PROP_USER_AREA;
    registrations.push_back(context->registerService<CFSLocation>(location, locationProperties));
  }
  location = CFSLocationManager::getInstanceLocation();
  if (location != NULL)
  {
    locationProperties["type"] = CFSPluginFrameworkLauncher::PROP_INSTANCE_AREA;
    registrations.push_back(context->registerService<CFSLocation>(location, locationProperties));
  }
  location = CFSLocationManager::getConfigurationLocation();
  if (location != NULL)
  {
    locationProperties["type"] = CFSPluginFrameworkLauncher::PROP_CONFIG_AREA;
    registrations.push_back(context->registerService<CFSLocation>(location, locationProperties));
  }
  location = CFSLocationManager::getInstallLocation();
  if (location != NULL)
  {
    locationProperties["type"] = CFSPluginFrameworkLauncher::PROP_INSTALL_AREA;
    registrations.push_back(context->registerService<CFSLocation>(location, locationProperties));
  }

  location = CFSLocationManager::getCFSHomeLocation();
  if (location != NULL)
  {
    locationProperties["type"] = CFSPluginFrameworkLauncher::PROP_HOME_LOCATION_AREA;
    registrations.push_back(context->registerService<CFSLocation>(location, locationProperties));
  }

  CFSPluginFrameworkDebugOptions* dbgOptions = CFSPluginFrameworkDebugOptions::getDefault();
  dbgOptions->start(context);
  context->registerService<CFSDebugOptions>(dbgOptions);
}

//----------------------------------------------------------------------------
void CFSPluginFrameworkPrivate::deactivate(CFSPluginContext* /*context*/)
{
  foreach(CFSServiceRegistration registration, registrations)
  {
    if (registration)
    {
      try
      {
        registration.unregister();
      }
      catch (const CFSIllegalStateException&) {}
    }
  }
}

//----------------------------------------------------------------------------
void CFSPluginFrameworkPrivate::uninitSystemPlugin()
{
  this->pluginContext->d_func()->invalidate();
}

//----------------------------------------------------------------------------
void CFSPluginFrameworkPrivate::shutdown(bool restart)
{
  Locker sync(&lock);

  bool wasActive = false;
  switch (state)
  {
  case CFSPlugin::INSTALLED:
  case CFSPlugin::RESOLVED:
    shutdownDone_unlocked(false);
    break;
  case CFSPlugin::ACTIVE:
    wasActive = true;
    // Fall through
  case CFSPlugin::STARTING:
    if (shuttingDown.fetchAndAddOrdered(0) == 0)
    {
      try
      {
        const bool wa = wasActive;
        shuttingDown.fetchAndStoreOrdered(1);
        QtConcurrent::run(this, &CFSPluginFrameworkPrivate::shutdown0, restart, wa);
      }
      catch (const CFSException& e)
      {
        systemShuttingdownDone(CFSPluginFrameworkEvent(CFSPluginFrameworkEvent::PLUGIN_ERROR,
                                                       this->q_func(), e));
      }
    }
    break;
  case CFSPlugin::STOPPING:
    // Shutdown already inprogress, fall through
  case CFSPlugin::UNINSTALLED:
    break;
  }
}

//----------------------------------------------------------------------------
void CFSPluginFrameworkPrivate::shutdown0(bool restart, bool wasActive)
{
  try
  {
    {
      Locker sync(&lock);
      waitOnOperation(&lock, QString("Framework::") + (restart ? "update" : "stop"), true);
      operation = DEACTIVATING;
      state = CFSPlugin::STOPPING;
    }

    fwCtx->listeners.emitPluginChanged(
        CFSPluginEvent(CFSPluginEvent::STOPPING, this->q_func()));

    if (wasActive)
    {
      stopAllPlugins();
      deactivate(this->pluginContext.data());
    }

    {
      Locker sync(&lock);
      fwCtx->uninit();
      shuttingDown.fetchAndStoreOrdered(0);
      shutdownDone_unlocked(restart);
    }

    if (restart)
    {
      if (wasActive)
      {
        q_func().toStrongRef()->start();
      }
      else
      {
        init();
      }
    }
  }
  catch (const CFSException& e)
  {
    shuttingDown.fetchAndStoreOrdered(0);
    systemShuttingdownDone(CFSPluginFrameworkEvent(CFSPluginFrameworkEvent::PLUGIN_ERROR,
                                                   this->q_func(), e));
  }
}

//----------------------------------------------------------------------------
void CFSPluginFrameworkPrivate::shutdownDone_unlocked(bool restart)
{
  CFSPluginFrameworkEvent::Type t = restart ? CFSPluginFrameworkEvent::FRAMEWORK_STOPPED_UPDATE : CFSPluginFrameworkEvent::FRAMEWORK_STOPPED;
  systemShuttingdownDone_unlocked(CFSPluginFrameworkEvent(t, this->q_func()));
}

//----------------------------------------------------------------------------
void CFSPluginFrameworkPrivate::stopAllPlugins()
{
  // TODO start level
//  if (fwCtx.startLevelController != null)
//  {
//    fwCtx.startLevelController.shutdown();
//  }

  // Stop all active plug-ins, in reverse plug-in ID order
  // The list will be empty when the start level service is in use.
  QList<QSharedPointer<CFSPlugin> > activePlugins = fwCtx->plugins->getActivePlugins();
  qSort(activePlugins.begin(), activePlugins.end(), pluginIdLessThan);
  QListIterator<QSharedPointer<CFSPlugin> > i(activePlugins);
  i.toBack();
  while(i.hasPrevious())
  {
    QSharedPointer<CFSPlugin> p = i.previous();
    try
    {
      if (p->getState() & (CFSPlugin::ACTIVE | CFSPlugin::STARTING))
      {
        // Stop plugin without changing its autostart setting.
        p->stop(CFSPlugin::STOP_TRANSIENT);
      }
    }
    catch (const CFSPluginException& pe)
    {
      fwCtx->listeners.frameworkError(p, pe);
    }
  }

  QList<QSharedPointer<CFSPlugin> > allPlugins = fwCtx->plugins->getPlugins();

  // Set state to INSTALLED and purge any unrefreshed bundles
  foreach (QSharedPointer<CFSPlugin> p, allPlugins)
  {
    if (p->getPluginId() != 0)
    {
      p->d_func()->setStateInstalled(false);
      p->d_func()->purge();
    }
  }
}

//----------------------------------------------------------------------------
void CFSPluginFrameworkPrivate::systemShuttingdownDone(const CFSPluginFrameworkEvent& fe)
{
  Locker sync(&lock);
  systemShuttingdownDone_unlocked(fe);
}

//----------------------------------------------------------------------------
void CFSPluginFrameworkPrivate::systemShuttingdownDone_unlocked(const CFSPluginFrameworkEvent& fe)
{

  if (state != CFSPlugin::INSTALLED)
  {
    state = CFSPlugin::RESOLVED;
    operation.fetchAndStoreOrdered(IDLE);
    lock.wakeAll();
  }
  stopEvent.isNull = fe.isNull();
  stopEvent.type = fe.getType();
}
